<?php

    namespace Admin\Controller;

    use Common\Controller\AdminbaseController;

    class AdminSaleController extends AdminbaseController {

        protected $m_sale_manager;
        protected $m_sale;

        function _initialize() {
            parent::_initialize();
            $this->m_sale_manager= D("Admin/SaleManager");
            $this->m_sale= D("Admin/Sale");
            $this->m_sale_good= D("Sale/SaleGood");
        }

        /**
         * 消费机构管理
         */
        public function index(){
            $keyword = I("request.keyword");
            $this->assign("keyword",$keyword);
            if(!empty($keyword)){
                $where['sale_name'] = array('like',"%$keyword%");
            }
            $s_smid = I("request.s_smid");
            $this->assign("s_smid",$s_smid);
            if(!empty($s_smid)){
                $where["sale_manager_id"] = $s_smid;
            }
            $sale_manager_list = $this->m_sale_manager->select();
            $this->assign("sale_manager_list",$sale_manager_list);

            if (session('ADMIN_ID') == '10') {
                $count=$this->m_sale->where($where)->withTrashed()->count();
            }else{
                $count=$this->m_sale->where($where)->count();
            }
            $page = $this->page($count, 15);
            $list = $this->m_sale->field("*")
                ->where($where)
                ->order("create_time desc")
                ->limit($page->firstRow , $page->listRows);
            // 如果是管理员可以看到删除的
            if (session('ADMIN_ID') == '10') {
                $list = $list->withTrashed()->order("sale_manager_id DESC,delete_time ASC,create_time DESC");
            }

            $list = $list->select();
            foreach($list AS &$item){
                $item["sale_manage_name"] = "";
                if($item["sale_manager_id"]>0){
                    $sale_manager = $this->m_sale_manager->where(array("id"=>$item["sale_manager_id"]))->find();
                    $item["sale_manage_name"]  = $sale_manager["sale_manage_name"];
                }
                $sale_goods = $this->m_sale_good->where(array('sale_id'=>$item['id']))->select();
                $item['sale_goods'] = $sale_goods;
            }
            $this->assign("page", $page->show('Admin'));
            $this->assign("list",$list);
            $this->display();
        }


        /**
         * 导入消费数据
         */
        public function sale_import(){
            $this->display();
        }

        /**
         * 导入消费数据
         */
        public function sale_import_post(){
            $nor_create_logistics = I("request.nor_create_logistics");

            $file = $_FILES['sale_file']['tmp_name'];
            $file_name = $_FILES['sale_file']['name'];
            $file_info = pathinfo($file_name);
            $file_type = $file_info['extension'];

            if($file_type != 'xls' && $file_type != 'xlsx'){
                $this->error("文件格式有误！");exit;
            }
            if(empty($file)){
                $this->error("文件不存在！");exit;
            }
            $excel = new \Common\Lib\excel($file);
            $sale_data_list = $excel->get_excel_data($file_type);
            if(empty($sale_data_list)){
                $this->error("文件数据为空！");exit;
            }

                //   `create_time` varchar(50) DEFAULT NULL,
                //   `lid` int(10) DEFAULT '0' COMMENT '卡片所属物流公司ID',
                //   `sale_id` int(10) DEFAULT NULL COMMENT '消费机构id',
                //   `sale_manager_id` int(10) DEFAULT '0' COMMENT '上级消费机构ID',
                //   `goods_name` varchar(50) DEFAULT NULL COMMENT '商品名称',
                //   `goods_unit_price` decimal(10,2) DEFAULT '0.00' COMMENT '商品单价',
                //   `goods_num` decimal(10,2) DEFAULT NULL COMMENT '商品数量',
                //   `goods_price` decimal(10,2) DEFAULT NULL COMMENT '商品总价',
                //   `dis_price` decimal(10,2) DEFAULT '0.00' COMMENT '优惠金额总额',
                //   `price` decimal(10,2) DEFAULT NULL COMMENT '消费金额',
                //   `desc` varchar(500) DEFAULT NULL COMMENT '充值描述',
                //   `card_number` varchar(50) DEFAULT NULL COMMENT '会员卡号',
                  
                // `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                //   `number` varchar(50) DEFAULT NULL COMMENT '账单号',
                //   `cid` int(11) DEFAULT NULL COMMENT '会员卡id',
                //   `general_point` int(11) DEFAULT NULL COMMENT '一号物流奖励积分',
                //   `self_point` int(10) DEFAULT NULL COMMENT '自营奖励积分',
                //   `plus_price` decimal(10,2) DEFAULT NULL COMMENT '剩余金额',
                //   `plus_point` int(10) DEFAULT NULL COMMENT '剩余积分',
                //   `uid` varchar(50) DEFAULT NULL COMMENT '销售登录用户ID',
                //   `admin_oil_discount` decimal(10,2) DEFAULT '0.00' COMMENT '管理员每升石油优惠金额',
                //   `pre_price` decimal(10,2) DEFAULT '0.00' COMMENT '优惠前订单总额',
                //   `goods_unit` char(255) DEFAULT '升' COMMENT '单位',
                //   `is_oil` char(255) DEFAULT '1' COMMENT '是否是油',
                //   `sale_price` decimal(10,2) DEFAULT '0.00' COMMENT '消费机构累计消费金额',
                //   `status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '是否有效：0无效，1有效',

            $name_column_list = array(

                '消费时间'=>'create_time',
                '卡片所属机构' => 'logistics_name',
                '消费机构' => 'sale_name',
                '会员卡号' => 'card_number',

                '商品名称' => 'goods_name',
                '产品单价' => 'goods_unit_price',
                '商品数量' => 'goods_num',
                '商品总价' => 'goods_price',
                '优惠金额' => 'dis_price',
                '账单支付金额' => 'price',

                '描述' => 'desc',
            );

            $sale_insert_data = array();

            foreach ($sale_data_list as $sale_data_row) {
                $temp_row = array();
                /*生成数据列*/
                foreach ($sale_data_row as $_key => $_value) {

                    if (isset($name_column_list[$_key])) {
                        $temp_row[$name_column_list[$_key]] = trim($_value);
                    }
                }
                if (!empty($temp_row)) {
                    $sale_insert_data[] = $temp_row;
                }
            }

            if (empty($sale_insert_data)) {
                $this->error('未检索到有效数据');
            }

            /*批量查询消费机构*/
            $to_sale_list = array_unique(array_column($sale_insert_data, 'sale_name'));
            $sale_infos = M("sale")->where(array("sale_name"=>array('in',$to_sale_list)))->fetchSql(false)->select();
            if (empty($sale_infos)) {
                $this->error('消费机构都未查到：'.implode(',', array_unique(array_column($sale_insert_data, 'sale_name'))));
            }elseif (count($to_sale_list) != count($sale_infos)) {
                $finded_sale_list = array_unique(array_column($sale_infos, 'sale_name'));
                $cnt_find = array_diff($to_sale_list, $finded_sale_list);
                $this->error('部分消费机构未查到：'.implode(',', $cnt_find));
            }else{
                $sale_infos_list = array();
                foreach ($sale_infos as $_key => $_row) {
                    $sale_infos_list[$_row['sale_name']] = $_row;
                }
            }
            /*批量查询上级消费机构*/
            // $sale_manager_infos = DB::name("sale_manager")->where(array("sale_manager_id"=>array('in',array_unique(array_column($sale_infos, 'sale_manager_id')))))->fetchSql(false)->select();
            // if (empty($sale_infos)) {
            //     $this->error('未查询到消费机构');
            // }else{
            //     $sale_manager_infos_list = array();
            //     foreach ($sale_manager_infos as $_key => $_row) {
            //         $sale_manager_infos_list[$_row['sale_manager_id']] = $_row;
            //     }
            // }

            if ($nor_create_logistics) {
                $logistics_name_lists = array_unique(array_column($sale_insert_data, 'logistics_name'));
                foreach ($logistics_name_lists as $_key => $logistics_name) {
                    $nor_logi_res = M("logistics")->where(array("logistics_name"=>$logistics_name))->fetchSql(false)->select();
                    if (empty($nor_logi_res)) {

                        $logi_insert['logistics_name'] = $logistics_name;
                        $logi_insert['balance'] = rand(1000,500000);

                        $logi_insert['create_time'] =  mt_rand(strtotime('2017-1-1'),strtotime('2018-10-1'));
                        $logi_insert['total_card_num'] = rand(500,2500);
                        $logi_insert['active_card_num'] = rand(250,$logi_insert['total_card_num']);

                        $result = D("Admin/Logistics")->add($logi_insert);

                        if(!$result){
                            $this->error('物流公司创建失败：'.$logistics_name);
                        }
                    }
                }
            }

            /*批量查询卡片所属机构*/
            $logistics_infos = M("logistics")->where(array("logistics_name"=>array('in',array_unique(array_column($sale_insert_data, 'logistics_name')))))->fetchSql(false)->select();
            if (empty($logistics_infos)) {
                $this->error('所属机构都未查到：'.implode(',', array_unique(array_column($sale_insert_data, 'logistics_name'))));
            }else{
                $logistics_infos_list = array();
                foreach ($logistics_infos as $_key => $_row) {
                    $logistics_infos_list[$_row['logistics_name']] = $_row;
                }
            }

            $card_count = array();
            foreach ($sale_insert_data as $_key => $_row) {
                if (!isset($logistics_infos_list[$_row['logistics_name']])) {
                    $this->error('未查询到所属机构：'.$_row['logistics_name']);
                }

                $logistic_info = $logistics_infos_list[$_row['logistics_name']];

                $card_count[$logistic_info['id']] ++; 
            }


            /*随机卡号数据*/
            $card_infos_res = M("card")->query('SELECT * FROM `bdt_card` where 1=1 ORDER BY RAND() limit '.count($sale_insert_data));

            $admin_card_sale_point = get_config_by_key('admin_card_sale_point');
            $logistics_card_sale_point = get_config_by_key('logistics_card_sale_point');

            foreach ($sale_insert_data as $_key => &$_row) {

                /*消费机构数据*/
                $sale_info = $sale_infos_list[$_row['sale_name']];

                /*物流公司数据*/
                $logistic_info = $logistics_infos_list[$_row['logistics_name']];

                
                $card_info = $card_infos_res[$_key];

                /*积分计算*/
                $sale_point_line = $sale_info['point_line']; // 个人卡消费积分奖励线
                // 总积分
                $general_point = ceil($_row['price']/100 * $admin_card_sale_point);
                // 自营积分
                $self_point = ceil($_row['price']/100 * $logistics_card_sale_point);
                // 个人卡消费机构奖励积分
                if ($sale_point_line > 0 && $logistic_info['id'] == 1) {
                    $general_point += floor($_row['price'] / $sale_point_line);
                }

                // 应得积分
                $point = $general_point + $self_point;

                // 卡内余额
                $plus_price = round($card_info['balance']-$_row['price'],2);
                $plus_price = $plus_price>0?$plus_price:0;
                // 卡内积分
                $plus_point = $card_info['use_point']+$point;

                // 消费时间
                $create_time = strtotime($_row['create_time']);
                // 订单号
                $number = date("YmdHis",$create_time).rand(10000,99999);
                // 操作者
                $uid = $uid?$uid:session('ADMIN_ID');

                /*补充数据*/
                $_row['number'] = $number;   // 账单号
                $_row['cid'] = $card_info['id'];  // 会员卡id
                $_row['card_number'] = $card_info['number'];  // 会员卡id
                $_row['general_point'] = $general_point;    // 一号物流奖励积分
                $_row['self_point'] = $self_point;   // 自营奖励积分
                $_row['plus_price'] = $plus_price;   // 剩余金额
                $_row['plus_point'] = $plus_point;   // 剩余积分
                $_row['uid'] = $uid;  // 销售登录用户ID
                // $_row['admin_oil_discount'] = '';   // 管理员每升石油优惠金额
                // $_row['pre_price'] = '';    // 优惠前订单总额
                $_row['goods_unit'] = '公斤';   // 单位
                $_row['is_oil'] = '0';   // 是否是油
                // $_row['sale_price'] = '';   // 消费机构累计消费金额
                $_row['status'] = '1';   // 是否有效：0无效，1有效
                
                $_row['create_time'] = $create_time;   // 账单号
                $_row['lid'] = $logistic_info['id'];   // 账单号
                $_row['sale_id'] = $sale_info['id'];   // 账单号
                $_row['sale_manager_id'] = $sale_info['sale_manager_id'];   // 账单号
                unset($_row['logistics_name']);
                unset($_row['sale_name']);

                $_row['goods_name'] = $_row['goods_name']?$_row['goods_name']:'LNG';
                // $_row['goods_unit_price'] => '';
                $_row['goods_num'] = $_row['goods_num'] > 0?$_row['goods_num']:round($_row['goods_price'] / $_row['goods_unit_price'],2);
                // $_row['goods_price'] => '';
                // $_row['dis_price'] => '';
                // $_row['price'] => '';

                // $_row['desc'] => '';
                $_row['status'] = '1';

            }
            $res = M('card_sale')->addAll($sale_insert_data);

            // $logistics = M("Logistics")->where(array("id"=>get_logistics_id()))->find();
            
            $this->success("操作成功！");
        }

        // 添加
        public function add(){
            $id = I("get.id",0,'intval');
            if(!empty($id)){
                $item=$this->m_sale->where(array('id'=>$id))->find();
                $this->assign("item",$item);
            }
            $sale_manager_list = $this->m_sale_manager->select();
            $this->assign("sale_manager_list",$sale_manager_list);
            $this->display();
        }

        // 提交
        public function add_post(){
            if (IS_POST) {
                $id = I("post.id");
                $insert = I("post.");

                if(empty($id)){
                    $insert['create_time'] =time();
                    $result =$this->m_sale->add($insert);
                }else{

                    $result = $this->m_sale->where(array("id"=>$id))->save($insert);
                }
                if ($result) {
                    $this->success("添加成功！");
                } else {
                    $this->error("添加失败！");
                }

            }
        }

        // 删除
        public function delete(){
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                if ($this->m_sale->where(array('id'=>$id))->delete() !==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }else{
                $this->error("参数有误！");
            }

        }

        /*彻底删除就是把软删除关了，感觉理论上应该没错*/
        public function overdelete(){
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                if ($this->m_sale->delete($id,true)!==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }else{
                $this->error("参数有误！");
            }
        }

        /*彻底删除就是把软删除关了*/
        public function restore(){
            $id = I('get.id',0,'intval');

            $result = $this->m_sale->restore($id);

            if ($result) {
                $this->success("数据已恢复！");
            }else{
                $this->success("数据恢复失败！");
            }
        }
    }